package com.linkage.jz.bankruptcy.activity.Vote;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteDetail;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteRule;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.datepicker.CustomDatePicker;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;
import com.linkage.seapeak.activity.vote.EditVoteMemberGroupActivity;
import com.linkage.seapeak.activity.vote.EditVoteMemberNoGroupActivity;
import com.linkage.seapeak.pojo.UploadImage;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.linkage.jz.bankruptcy.net.Network.getAPIService;

/**
 * @author AFAP
 * 新建表决
 */
public class ProVoteNewVoteActivity extends BaseCreateActivity implements View.OnClickListener {
    private final String TAG = "TAG";

    public static final String KEY_ACTION = "action";
    public static final String KEY_PROJECTTYPE = "KEY_PROJECTTYPE";
    public static final String KEY_VOTE = "vote";

    private final int REQUEST_CODE_RULE = 10001;
    private final int REQUEST_CODE_MEMBER = 10002;
    private final int REQUEST_CODE_GROUP = 10003;

    // 新建的时候临时创建的表决ID
    private String mTempVoteId;
    private String mProjectID;
    private String mProjectType;
    private ProVoteDetail mProVoteDetail;

    private RecyclerView mImgRecyclerView;
    private ArrayList<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter mImgAdapter;

    private List<ProVoteRule> mRuleList = new ArrayList<>();
    private ProVoteRule mRule = new ProVoteRule();


    private EditText et_vote_name, tv_vote_rule_desc, et_vote_desc, et_vote_presetTime;
    private TextView tv_vote_rule, tv_vote_time_start, tv_vote_time_end, tv_vote_time_notice,
            tv_vote_member;
    private CheckBox ck_vote_noticeSms, ck_vote_noticeOfflineSms, ck_vote_noticeMessage;
    private Switch switch_vote_committeeVisible;


    private Date tenYearLater;//日期选择跨度10年（可修改）

    private long mTimeStart = -1, mTimeEnd = -1, mTimeNotice = -1; // 开始时间、结束时间、通知时间
    private int mType = -1; // 表决类型 1-债权人会议表决,2-债权人委员会表决
    private boolean mDefaultAgreed = false; // 参会未表决默认同意

    private int mMemberCount = 0;
    private int mTimeMode = 1; // 通知时间方式 1-指定时间,2-待定
    private boolean mCourtHolding = true;
    private boolean mNoticeSms = false;
    private boolean mNoticeOfflineSms = false;
    private boolean mNoticeMessage = false;
    private boolean mCommitteeVisible = false;
    private boolean mGenMeetingNo = false; // TODO

    private CommonPromptDialog mPromptDialog;

    @Override
    public void initData() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 10);
        tenYearLater = calendar.getTime();
    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_vote_new_vote);
        super.onCreate(savedInstanceState);
        titlebar_title.setText("新建表决事项");


        if (TextUtils.equals(getIntent().getStringExtra(KEY_ACTION), "edit")) {
            mProVoteDetail = (ProVoteDetail) getIntent().getSerializableExtra(KEY_VOTE);
            mProjectID = mProVoteDetail.getBankruptcyProjectId();
        } else {
            mProjectID = getIntent().getStringExtra(KEY_PROJECTID);
            mProjectType = getIntent().getStringExtra(KEY_PROJECTTYPE);
        }
        if (mProVoteDetail != null) {
            titlebar_title.setText("编辑表决事项");
        } else {
            titlebar_title.setText("新建表决事项");
            mTempVoteId = UUID.randomUUID().toString().replaceAll("-", "");
        }

        mRule.setType(-1);
        initViews();
        titlebar_menu_text.setOnClickListener(this);
        tv_vote_member.setOnClickListener(this);

        getRuleList(null);
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        mPromptDialog = new CommonPromptDialog(this, CommonPromptDialog.TYPE_TIPS);
        mPromptDialog.setContent("放弃编辑？");
        mPromptDialog.setPositiveClickListener("是", view -> ProVoteNewVoteActivity.super.onBackPressed());
        mPromptDialog.setNegativeClickListener("否", view -> mPromptDialog.dismiss());
        mPromptDialog.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_RULE:
                    ProVoteRule bean = (ProVoteRule) data.getSerializableExtra("rule");
                    mRuleList.add(bean);
                    mRule = (ProVoteRule) data.getSerializableExtra("rule");
                    getRuleList(mRule.getName());
                    tv_vote_rule.setText(mRule.getName());
                    tv_vote_rule_desc.setText(mRule.getExplains());
                    break;
                case REQUEST_CODE_MEMBER:
                    mMemberCount = data.getIntExtra("count", 0);
                    tv_vote_member.setText(mMemberCount + "人");
                    break;
                case REQUEST_CODE_GROUP:
                    mMemberCount = data.getIntExtra("count", 0);
                    tv_vote_member.setText(mMemberCount + "人");
                    break;
            }
        }
    }

    private void getRuleList(String ruleName) {
        Network
                .getAPIService()
                .getVoteRuleList(getUserToken(), mProjectID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonArray arr = json.getAsJsonArray("data");
                        List<ProVoteRule> list = ProVoteRule.parse(arr);
                        mRuleList.clear();
                        mRuleList.addAll(list);

                        if (mProVoteDetail != null) {
                            for (ProVoteRule rule : mRuleList) {
                                if (TextUtils.equals(rule.getName(), mProVoteDetail.getRuleName())) {
                                    tv_vote_rule.setText(rule.getName());
                                    tv_vote_rule_desc.setText(rule.getExplains());
                                    mRule = rule;
                                }
                            }
                        } else if (!TextUtils.isEmpty(ruleName)) {
                            for (ProVoteRule rule : mRuleList) {
                                if (TextUtils.equals(rule.getName(), ruleName)) {
                                    tv_vote_rule.setText(rule.getName());
                                    tv_vote_rule_desc.setText(rule.getExplains());
                                    mRule = rule;
                                }
                            }
                        } else {
                            setDefaultRule();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }

    private void resetMember() {
        // 编辑时不可改类型和规则，不需要重置
        if (mProVoteDetail != null) {
            return;
        }
        mTempVoteId = UUID.randomUUID().toString().replaceAll("-", "");
        mMemberCount = 0;
        tv_vote_member.setText(null);
    }

    // 设置默认规则
    private void setDefaultRule() {
        // 编辑不给改规则
        if (mProVoteDetail != null) {
            return;
        }
        mRule = null;
        tv_vote_rule.setText(null);
        tv_vote_rule_desc.setText(null);

        LogUtil.v(TAG, "设置默认规则,mProjectType:" + mProjectType);
        String typeName = "";
        if (TextUtils.equals(mProjectType, "0")) {
            typeName = "清算";
        } else if (TextUtils.equals(mProjectType, "1")) {
            typeName = "重整";
        } else if (TextUtils.equals(mProjectType, "2")) {
            typeName = "和解";
        } else if (TextUtils.equals(mProjectType, "3")) { // 其实是其他
            typeName = "清算";
        }

        if (mRuleList.size() == 0) {
            LogUtil.w(TAG, "可选规则为0，等等吧");
            return;
        }
        if (mType == 2) {
            for (int i = 0; i < mRuleList.size(); i++) {
                if (mRuleList.get(i).getName().contains("债权人委员会表决")) {
                    mRule = mRuleList.get(i);
                    tv_vote_rule.setText(mRule.getName());
                    tv_vote_rule_desc.setText(mRule.getExplains());
                    break;
                }
            }
        } else if (mType == 1 && !TextUtils.isEmpty(typeName)) { // 新建时有项目类型，且这个时候才能选择规则
            for (int i = 0; i < mRuleList.size(); i++) {
                if (mRuleList.get(i).getName().contains(typeName)) {
                    mRule = mRuleList.get(i);
                    tv_vote_rule.setText(mRule.getName());
                    tv_vote_rule_desc.setText(mRule.getExplains());
                    break;
                }
            }
        }
    }


    public void initViews() {
        // 特殊处理下，
        titlebar_back.setOnClickListener(view -> onBackPressed());
        titlebar_menu_text.setVisibility(View.VISIBLE);

        et_vote_name = findViewById(R.id.et_vote_name);
        et_vote_desc = findViewById(R.id.et_vote_desc);
        et_vote_presetTime = findViewById(R.id.et_vote_presetTime);
        tv_vote_rule = findViewById(R.id.tv_vote_rule);
        tv_vote_rule_desc = findViewById(R.id.tv_vote_rule_desc);
        tv_vote_time_start = findViewById(R.id.tv_vote_time_start);
        tv_vote_time_end = findViewById(R.id.tv_vote_time_end);
        tv_vote_time_notice = findViewById(R.id.tv_vote_time_notice);
        tv_vote_member = findViewById(R.id.tv_vote_member);
        switch_vote_committeeVisible = findViewById(R.id.switch_vote_committeeVisible);
        ck_vote_noticeSms = findViewById(R.id.ck_vote_noticeSms);
        ck_vote_noticeOfflineSms = findViewById(R.id.ck_vote_noticeOfflineSms);
        ck_vote_noticeMessage = findViewById(R.id.ck_vote_noticeMessage);

        mImgRecyclerView = findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView.setLayoutManager(manager);
        mImgAdapter = new GridImagesAdapter(this, TYPE_EDIT);
        mImgAdapter.setList(mImgList);
        mImgRecyclerView.setAdapter(mImgAdapter);

        ((RadioGroup) findViewById(R.id.rg_vote_type)).setOnCheckedChangeListener((radioGroup, which) -> {
            if (which == R.id.rg_vote_type_1) {
                mType = 1;
                findViewById(R.id.area_committeeVisible).setVisibility(View.GONE);
                ((RadioButton) findViewById(R.id.rg_vote_courtHolding_1)).setChecked(true);
                setDefaultRule();
                resetMember();
            } else if (which == R.id.rg_vote_type_2) {
                mType = 2;
                findViewById(R.id.area_committeeVisible).setVisibility(View.VISIBLE);
                ((RadioButton) findViewById(R.id.rg_vote_courtHolding_2)).setChecked(true);
                setDefaultRule();
                resetMember();
            }
        });
        ((RadioGroup) findViewById(R.id.rg_vote_notice_time_mode)).setOnCheckedChangeListener((radioGroup, which) -> {
            if (which == R.id.rg_vote_notice_time_mode_1) {
                mTimeMode = 1;
                findViewById(R.id.area_time_notice).setVisibility(View.VISIBLE);
            } else if (which == R.id.rg_vote_notice_time_mode_2) {
                mTimeMode = 2;
                findViewById(R.id.area_time_notice).setVisibility(View.GONE);
            }
        });
        ((RadioGroup) findViewById(R.id.rg_vote_courtHolding)).setOnCheckedChangeListener((radioGroup, which) -> mCourtHolding = which == R.id.rg_vote_courtHolding_1);
        ((CheckBox) findViewById(R.id.ck_vote_defaultAgreed)).setOnCheckedChangeListener((compoundButton, b) ->
                mDefaultAgreed = b);
        switch_vote_committeeVisible.setOnCheckedChangeListener((compoundButton, b) -> mCommitteeVisible = b);
        ck_vote_noticeSms.setOnCheckedChangeListener((compoundButton, b) -> mNoticeSms = b);
        ck_vote_noticeOfflineSms.setOnCheckedChangeListener((compoundButton, b) -> mNoticeOfflineSms = b);
        ck_vote_noticeMessage.setOnCheckedChangeListener((compoundButton, b) -> mNoticeMessage = b);

        if (mProVoteDetail != null) {
            // 设置不可修改项目
            findViewById(R.id.rg_vote_type_1).setEnabled(false);
            findViewById(R.id.rg_vote_type_2).setEnabled(false);
            findViewById(R.id.tv_vote_rule).setEnabled(false);
            findViewById(R.id.tv_vote_rule_desc).setEnabled(false);
            findViewById(R.id.tv_public_type_add).setVisibility(View.GONE);

            mRule.setType(mProVoteDetail.getRule());
            mRule.setName(mProVoteDetail.getRuleName());
            mRule.setExplains(mProVoteDetail.getRuleExplain());
            mRule.setGrouped(mProVoteDetail.isGrouped() ? 1 : 0);

            tv_vote_rule.setText(mRule.getName());
            tv_vote_rule_desc.setText(mRule.getExplains());

            et_vote_name.setText(mProVoteDetail.getTitle());
            if (mProVoteDetail.getType() == 1) {
                ((RadioButton) findViewById(R.id.rg_vote_type_1)).setChecked(true);
            } else {
                ((RadioButton) findViewById(R.id.rg_vote_type_2)).setChecked(true);
            }
            et_vote_desc.setText(mProVoteDetail.getContent());
            ((CheckBox) findViewById(R.id.ck_vote_defaultAgreed)).setChecked(mProVoteDetail.isDefaultAgreed());
            if (mProVoteDetail.getFiles() != null) {
                for (TaskAtta atta : mProVoteDetail.getFiles()) {
                    UploadImage img = new UploadImage();
                    img.setFilename(atta.getAttachmentName());
                    img.setFilepath(atta.getAttachmentDownloadAddress());
                    img.setFilesize(atta.getAttachmentSize());
                    img.setLoadUrl(atta.getAttachmentPreviewAddress());
                    mImgList.add(img);
                    BaseCreateActivity.sorFiles(mImgList, true);
                }
                mImgAdapter.notifyDataSetChanged();
            }
            mTimeStart = mProVoteDetail.getStartTime() * 1000;
            tv_vote_time_start.setText(DateFormatUtils.long2Str(mProVoteDetail.getStartTime(), true));
            mTimeEnd = mProVoteDetail.getEndTime() * 1000;
            tv_vote_time_end.setText(DateFormatUtils.long2Str(mProVoteDetail.getEndTime(), true));

            tv_vote_member.setText(mProVoteDetail.getMemberTotal() + "人");
            if (mProVoteDetail.getTimeMode() == 1) {
                ((RadioButton) findViewById(R.id.rg_vote_notice_time_mode_1)).setChecked(true);
                mTimeNotice = mProVoteDetail.getNotificationTime() * 1000;
                tv_vote_time_notice.setText(DateFormatUtils.long2Str(mProVoteDetail.getNotificationTime(), true));
            } else {
                ((RadioButton) findViewById(R.id.rg_vote_notice_time_mode_2)).setChecked(true);
            }
            ck_vote_noticeSms.setChecked(mProVoteDetail.isNoticeSms());
            ck_vote_noticeOfflineSms.setChecked(mProVoteDetail.isNoticeOfflineSms());
            ck_vote_noticeMessage.setChecked(mProVoteDetail.isNoticeMessage());

            if (mProVoteDetail.isCourtHolding()) {
                ((RadioButton) findViewById(R.id.rg_vote_courtHolding_1)).setChecked(true);
            } else {
                ((RadioButton) findViewById(R.id.rg_vote_courtHolding_2)).setChecked(true);
            }
            et_vote_presetTime.setText("" + mProVoteDetail.getPresetTime());
            GetDetail(mProVoteDetail.getId(), mProVoteDetail.getRule() + "");
        } else {
            // 初始化几个默认值
            ((RadioButton) findViewById(R.id.rg_vote_type_1)).setChecked(true);
            ((RadioButton) findViewById(R.id.rg_vote_courtHolding_1)).setChecked(true);
            ck_vote_noticeOfflineSms.setChecked(true);
            ck_vote_noticeMessage.setChecked(true);
            mTimeNotice = System.currentTimeMillis();
            tv_vote_time_notice.setText(DateFormatUtils.long2Str(mTimeNotice, true));
        }

    }

    @Override
    public void onClick(View v) {
        CustomDatePicker mDatePicker;

        Intent intent;
        switch (v.getId()) {
            case R.id.titlebar_menu_text:
                saveData();
                break;
            case R.id.tv_vote_time_start:
                long end = tenYearLater.getTime();
                if (mTimeEnd > 0) {
                    end = mTimeEnd;
                }
                // 通过时间戳初始化日期，毫秒级别
                mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        mTimeStart = timestamp;
                        tv_vote_time_start.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, System.currentTimeMillis(), end);
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                mDatePicker.show(DateFormatUtils.long2Str(mTimeStart, true));
                break;
            case R.id.tv_vote_time_end:
                long start = System.currentTimeMillis();
                if (mTimeStart > 0) {
                    start = mTimeStart;
                }
                // 通过时间戳初始化日期，毫秒级别
                mDatePicker = new CustomDatePicker(this, timestamp -> {
                    mTimeEnd = timestamp;
                    tv_vote_time_end.setText(DateFormatUtils.long2Str(timestamp, true));
                }, start, tenYearLater.getTime());
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                mDatePicker.show(DateFormatUtils.long2Str(mTimeEnd, true));
                break;
            case R.id.tv_vote_time_notice:
                String mTimeStartStr = tv_vote_time_start.getText().toString().trim();
                if (TextUtils.isEmpty(mTimeStartStr)) {
                    ToastUtil.showShort("请选择开始时间");
                    return;
                }

                // 当前之后，开始时间之前
                mDatePicker = new CustomDatePicker(this, timestamp -> {
                    mTimeNotice = timestamp;
                    tv_vote_time_notice.setText(DateFormatUtils.long2Str(timestamp, true));
                }, System.currentTimeMillis(), mTimeStart);
                mDatePicker.setCancelable(false);
                mDatePicker.setCanShowPreciseTime(true);
                mDatePicker.setScrollLoop(false);
                mDatePicker.setCanShowAnim(false);
                if (mTimeNotice == -1) {
                    mTimeNotice = System.currentTimeMillis();
                }
                mDatePicker.show(DateFormatUtils.long2Str(mTimeNotice, true));
                break;
            case R.id.tv_vote_rule:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请选择表决规则");
                if (mRuleList.size() == 0) {
                    ToastUtil.showShort("无表决规则可选项");
                    return;
                }
                final String[] strRules = new String[mRuleList.size()];
                for (int i = 0; i < mRuleList.size(); i++) {
                    strRules[i] = mRuleList.get(i).getName();
                }
                builder.setItems(strRules, (dialog, which) -> {
                    if (mRule != null && mRule.getId() == mRuleList.get(which).getId()) {
                        // 没改变选项，不需要重新选
                    } else {
                        mRule = mRuleList.get(which);
                        tv_vote_rule.setText(mRule.getName());
                        tv_vote_rule_desc.setText(mRule.getExplains());
                        resetMember();
                    }


                });
                builder.show();
                break;
            case R.id.tv_public_type_add:
                intent = new Intent(this, ProVoteNewRuleActivity.class);
                intent.putExtra(KEY_PROJECTID, mProjectID);
                startActivityForResult(intent, REQUEST_CODE_RULE);
                break;
            case R.id.tv_vote_member:
                if (mProVoteDetail != null) {
                    if (mProVoteDetail.isGrouped()) {
                        intent = new Intent(this, EditVoteMemberGroupActivity.class);
                        intent.putExtra("projectId", mProjectID);
                        intent.putExtra("voteRule", mProVoteDetail.getRule());
                        intent.putExtra("voteId", mProVoteDetail.getId());
                        intent.putExtra("voteType", mProVoteDetail.getType());
                        startActivityForResult(intent, REQUEST_CODE_GROUP);
                    } else {
                        intent = new Intent(this, EditVoteMemberNoGroupActivity.class);
                        intent.putExtra("projectId", mProjectID);
                        intent.putExtra("voteRule", mProVoteDetail.getRule());
                        intent.putExtra("voteId", mProVoteDetail.getId());
                        intent.putExtra("voteType", mProVoteDetail.getType());
                        startActivityForResult(intent, REQUEST_CODE_MEMBER);
                    }
                } else {
                    if (mRule == null || mRule.getType() == -1) {
                        ToastUtil.showShort("请先选择表决规则");
                        return;
                    }
                    if (mRule.getGrouped() == 1) {
                        intent = new Intent(this, EditVoteMemberGroupActivity.class);
                        intent.putExtra("projectId", mProjectID);
                        intent.putExtra("voteRule", mRule.getType());
                        intent.putExtra("voteType", mType);
                        intent.putExtra("voteId", mTempVoteId);
                        startActivityForResult(intent, REQUEST_CODE_GROUP);
                    } else {
                        intent = new Intent(this, EditVoteMemberNoGroupActivity.class);
                        intent.putExtra("projectId", mProjectID);
                        intent.putExtra("voteRule", mRule.getType());
                        intent.putExtra("voteId", mTempVoteId);
                        intent.putExtra("voteType", mType);
                        startActivityForResult(intent, REQUEST_CODE_MEMBER);
                    }
                }

                break;
        }
    }


    public void saveData() {

        if (mType == -1) {
//            ToastUtil.showShort("请选择表决类型");
            showToast("请选择表决类型", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        String vote_name = et_vote_name.getText().toString().trim();
        String vote_desc = et_vote_desc.getText().toString().trim();
        if (TextUtils.isEmpty(vote_name)) {
//            ToastUtil.showShort("表决名称不能为空");
            showToast("表决名称不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
//        if (TextUtils.isEmpty(vote_desc)) {
//            ToastUtil.showShort("表决内容不能为空");
//            return;
//        }

        if (mRule.getType() == -1) {
//            ToastUtil.showShort("请选择表决规则类型");
            showToast("请选择表决规则类型", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        String mRuleName = tv_vote_rule.getText().toString().trim();
        if (TextUtils.isEmpty(mRuleName)) {
//            ToastUtil.showShort("表决规则名称不能为空");
            showToast("表决规则名称不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }


        int mRuleType = mRule.getType();
        String mRuleExplain = tv_vote_rule_desc.getText().toString().trim();
        String mSysRuleId = mRule.getId();


        double mMoneyPercent = mRule.getMoneyPercent();
        double personnelPercent = mRule.getPersonnelPercent();

        String mTimeStartStr = tv_vote_time_start.getText().toString().trim();
        String mTimeEndStr = tv_vote_time_end.getText().toString().trim();
        String mTimeNoticeStr = tv_vote_time_notice.getText().toString().trim();

        if (TextUtils.isEmpty(mTimeStartStr)) {
//            ToastUtil.showShort("请选择开始时间");
            showToast("请选择开始时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (TextUtils.isEmpty(mTimeEndStr)) {
//            ToastUtil.showShort("请选择结束时间");
            showToast("请选择结束时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (mTimeStart > mTimeEnd) {
//            ToastUtil.showShort("开始时间不得晚于结束时间");
            showToast("开始时间不得晚于结束时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (mTimeMode == 1 && mTimeNotice > mTimeStart) {
//            ToastUtil.showShort("通知时间不得晚于开始时间");
            showToast("通知时间不得晚于开始时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        if (mProVoteDetail == null && mMemberCount == 0) {
//            ToastUtil.showShort("请选择表决人员");
            showToast("请选择表决人员", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        if (mTimeMode == 1 && TextUtils.isEmpty(mTimeNoticeStr)) {
//            ToastUtil.showShort("请选择通知时间");
            showToast("请选择通知时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (mTimeMode == 2) {
            // TODO 即使是待定，这个时间也必须符合要求……
            mTimeNoticeStr = DateFormatUtils.long2Str(System.currentTimeMillis(), true);
        }
        int mPresetTime;
        try {
            mPresetTime = Integer.parseInt(et_vote_presetTime.getText().toString());
            if (mPresetTime < 0 || mPresetTime > 72) {
//                ToastUtil.showShort("预设时间范围是0-72小时");
                showToast("预设时间范围是0-72小时", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
                return;
            }
        } catch (Exception e) {
//            ToastUtil.showShort("请输入正确的预设时间");
            showToast("请输入正确的预设时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
//        mShapeLoadingDialog.setLoadingText("提交信息中...");
//        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
//        mShapeLoadingDialog.show();

//        JSONArray fileArr = new JSONArray();
//        for (int i = 1; i < mImgList.size(); i++) {
//            fileArr.put(mImgList.get(i).parse2JSON());
//        }
        JSONArray fileArr = new JSONArray();
        for (int i = 0; i < mImgList.size(); i++) {
            if (TextUtils.equals(mImgList.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(mImgList.get(i).getFilename())) {
                    obj.putOpt("filename", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("filename", mImgList.get(i).getFilename());
                }
                obj.putOpt("filepath", mImgList.get(i).getFilepath());
                obj.putOpt("filesize", mImgList.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        Observable<JsonObject> observable = null;
        if (mProVoteDetail != null) {
            observable = Network
                    .getAPIService()
                    .editVote_Manager(getUserToken(), mProVoteDetail.getId(), vote_name, vote_desc, mRuleName, mDefaultAgreed, mRuleExplain, mTimeStartStr + ":00", mTimeEndStr +
                                    ":00", fileArr.toString(),
                            mTimeMode, mTimeMode == 1 ? mTimeNoticeStr + ":00" : "", mCourtHolding, mPresetTime,
                            mNoticeSms,
                            mNoticeOfflineSms, mNoticeMessage, mGenMeetingNo);
        } else {
            observable = getAPIService()
                    .createVote_Manager(getUserToken(), mProjectID, mTempVoteId, vote_name, vote_desc, mType,
                            mRuleType, mRuleName, mDefaultAgreed, mRuleExplain,
                            mTimeStartStr + ":00", mTimeEndStr + ":00",
//                            mMembers.toString(),
                            fileArr.toString(), mTimeMode, mTimeMode == 1 ? mTimeNoticeStr + ":00" : "",
                            mCourtHolding, mPresetTime,
//                            mGroups.toString(),
                            mSysRuleId, mMoneyPercent,
                            personnelPercent, mNoticeSms, mNoticeOfflineSms, mNoticeMessage,
//                            mGenMeetingNo,
                            mCommitteeVisible);
        }

        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_VOTE);
                        EventBus.getDefault().post(event);

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                if (mProVoteDetail != null) {
//                                    mPromptDialog = new CommonPromptDialog(ProVoteNewVoteActivity.this,
//                                            CommonPromptDialog.TYPE_TIPS);
//
//                                    mPromptDialog.setContent("表决事项已修改");
//                                    mPromptDialog.setIsCenter(true);
//                                    mPromptDialog.setmCloseListener(v -> finish());
//                                    mPromptDialog.show();
                                    noticeDialog = new PublicNoticeDialog(ProVoteNewVoteActivity.this, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
//                                            if (v.getId() == R.id.btn_save_notice) {
//
//                                            }
                                            noticeDialog.dismiss();
                                            finish();
                                        }
                                    }, 1, "提示", "表决事项已修改",
                                            "取消", "确定");
                                    noticeDialog.show();
                                } else {
//                                    mPromptDialog = new CommonPromptDialog(ProVoteNewVoteActivity.this,
//                                            CommonPromptDialog.TYPE_TIPS);
//                                    mPromptDialog.setContent("表决事项创建成功");
//                                    mPromptDialog.setPositiveClickListener("确定", view -> finish());
//                                    mPromptDialog.setNegativeClickListener("取消", view -> finish());
//                                    mPromptDialog.show();
                                    noticeDialog = new PublicNoticeDialog(ProVoteNewVoteActivity.this, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
//                                            if (v.getId() == R.id.btn_save_notice) {
//
//                                            }
                                            noticeDialog.dismiss();
                                            finish();
                                        }
                                    }, 1, "提示", "表决事项创建成功",
                                            "取消", "确定");
                                    noticeDialog.show();
                                }
                            }

                        });

                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }

    PublicNoticeDialog noticeDialog;

    private void GetDetail(String voteId, String voteRule) {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .voteedit(voteId, voteRule, userToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
//                        ToastUtil.showShort("提交成功");
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

}
